package org.example;

import javax.swing.*;
import javax.swing.filechooser.FileNameExtensionFilter;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.File;
import java.io.IOException;
import java.sql.DatabaseMetaData;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
 * 主窗口类
 */
public class MainWindow extends JFrame {
    private ExcelReader excelReader = new ExcelReader();
    private DatabaseManager dbManager = new DatabaseManager();
//    private DataMigrationService migrationService;
    private MappingRuleDAO mappingRuleDAO;
    private ConfigPersistenceService configPersistence;
    private ExecutorService migrationExecutor = Executors.newSingleThreadExecutor();

    public MainWindow() {
        // 检查是否为headless环境
        if (GraphicsEnvironment.isHeadless()) {
            throw new HeadlessException("当前环境不支持图形界面");
        }

        setTitle("数据迁移工具");
        setSize(1400, 800);
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        setLocationRelativeTo(null); // 居中显示
        initializeServices();
        setupUI();
        loadSavedConfigs();
    }

    private void initializeServices() {
        try {
            // 初始化数据库连接（使用默认配置）
            //dbManager.connect("mysql", "10.155.2.17", "13306", "ceprei-cloud-personnel-data", "ceprei_cloud_dev", "Isuperone#123");
            dbManager.connect("mysql", "10.155.2.47", "13306", "ceprei-cloud-personnel-data", "microservice", "Isuperone#123");

            // 初始化数据库结构
            initializeDatabaseSchema();

            // 初始化持久化服务
            configPersistence = new ConfigPersistenceService(dbManager);
            configPersistence.initializeDatabase();

            // 初始化映射规则DAO
            mappingRuleDAO = new MappingRuleDAO(dbManager.getConnection());
            
            // 初始化ExcelReader
            excelReader = new ExcelReader();

        } catch (SQLException e) {
            showMigrationError(MigrationException.ExceptionType.DATABASE_CONNECTION_ERROR, "数据库初始化失败", e.getMessage());
        }
    }
    
    /**
     * 初始化数据库表结构
     */
    private void initializeDatabaseSchema() {
        try {
            // 使用已有的dbManager连接
            String schemaSql = "CREATE TABLE IF NOT EXISTS mapping_rules (" +
                "id INTEGER PRIMARY KEY AUTOINCREMENT, " +
                "source_field TEXT NOT NULL, " +
                "target_field TEXT NOT NULL, " +
                "conversion_type TEXT, " +
                "enum_mapping TEXT, " +
                "date_format TEXT, " +
                "foreign_key_table TEXT, " +
                "foreign_key_column TEXT, " +
                "foreign_key_target_column TEXT, " +
                "target_type TEXT, " +
                "target_table TEXT NOT NULL)";
                
            try (Statement stmt = dbManager.getConnection().createStatement()) {
                stmt.execute(schemaSql);
            }
        } catch (SQLException e) {
            System.err.println("数据库表结构初始化失败: " + e.getMessage());
        }
    }

    private void loadSavedConfigs() {
        // 加载最近使用的文件
        List<String> recentFiles = configPersistence.getRecentFiles();
        // TODO: 将recentFiles添加到界面显示

        // 加载保存的数据库连接配置
        List<Map<String, Object>> connections = configPersistence.getAllConnections();
        // TODO: 将connections添加到界面显示
    }

    private void setupUI() {
        JTabbedPane tabbedPane = new JTabbedPane();

        // File Selection Panel - 现在整合到映射配置面板中
        // Database Connection Panel - 保持不变
        // Migration Panel - 保持不变

        // Mapping Configuration Panel - 修改为直接展示映射配置面板
        JPanel mappingPanel = new JPanel(new BorderLayout());
        
        // 直接添加MappingConfigPanel

        if (mappingRuleDAO != null && configPersistence != null && dbManager != null) {
            MappingConfigPanel mappingConfigPanel = new MappingConfigPanel(configPersistence, excelReader, mappingRuleDAO);
            mappingPanel.add(mappingConfigPanel, BorderLayout.CENTER);
        } else {
            JLabel errorLabel = new JLabel("请先建立数据库连接和初始化服务");
            errorLabel.setForeground(Color.RED);
            mappingPanel.add(errorLabel, BorderLayout.CENTER);
        }
        
        // 将映射配置面板作为标签页的一部分
        tabbedPane.addTab("映射配置", mappingPanel);

        // Database Connection Panel
        JPanel dbPanel = new JPanel(new GridLayout(6, 2));
        JComboBox<String> dbTypeComboBox = new JComboBox<>(new String[]{"MySQL", "PostgreSQL", "Oracle"});
        JTextField hostField = new JTextField();
        JTextField portField = new JTextField();
        JTextField dbField = new JTextField();
        JTextField userField = new JTextField();
        JPasswordField passField = new JPasswordField();
        JButton connectButton = new JButton("连接数据库");
        JTextArea dbLog = new JTextArea();

        dbPanel.add(new JLabel("数据库类型:"));
        dbPanel.add(dbTypeComboBox);
        dbPanel.add(new JLabel("主机:"));
        dbPanel.add(hostField);
        dbPanel.add(new JLabel("端口:"));
        dbPanel.add(portField);
        dbPanel.add(new JLabel("数据库/服务名:"));
        dbPanel.add(dbField);
        dbPanel.add(new JLabel("用户名:"));
        dbPanel.add(userField);
        dbPanel.add(new JLabel("密码:"));
        dbPanel.add(passField);
        dbPanel.add(connectButton);
        dbPanel.add(new JScrollPane(dbLog));

        connectButton.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                String dbType = (String) dbTypeComboBox.getSelectedItem();
                String host = hostField.getText();
                String port = portField.getText();
                String dbName = dbField.getText();
                String user = userField.getText();
                String password = new String(passField.getPassword());

                try {
                    dbManager.connect(dbType.toLowerCase(), host, port, dbName, user, password);
                    dbLog.setText("数据库连接成功!\n");
                    // Get metadata
                    DatabaseMetaData meta = dbManager.getConnection().getMetaData();
                    dbLog.append("数据库产品名称: " + meta.getDatabaseProductName() + "\n");
                    dbLog.append("版本: " + meta.getDatabaseProductVersion() + "\n");

                    // 保存连接配置
                    Map<String, String> connectionConfig = new HashMap<>();
                    connectionConfig.put("dbType", dbType);
                    connectionConfig.put("host", host);
                    connectionConfig.put("port", port);
                    connectionConfig.put("database", dbName);
                    connectionConfig.put("user", user);
                    // 注意：出于安全考虑，不建议保存密码
                    configPersistence.saveConnectionConfig("last_connection", connectionConfig);

                } catch (SQLException ex) {
                    showMigrationError(MigrationException.ExceptionType.DATABASE_CONNECTION_ERROR, "数据库连接失败", ex.getMessage());
                }
            }
        });

//        // Migration Panel
//        JPanel migrationPanel = new JPanel(new BorderLayout());
//        JButton migrateButton = new JButton("开始迁移");
//        MigrationProgressMonitor progressMonitor = new MigrationProgressMonitor(0);
//
//        migrateButton.addActionListener(e -> {
//            if (migrationService == null) {
//                JOptionPane.showMessageDialog(MainWindow.this, "请先建立数据库连接", "错误", JOptionPane.ERROR_MESSAGE);
//                return;
//            }
//            JFileChooser fc = new JFileChooser();
//            fc.setFileFilter(new FileNameExtensionFilter("Excel Files", "xls", "xlsx"));
//
//            // 创建并配置迁移任务
//            MigrationTask migrationTask = new MigrationTask(
//                "path_to_excel_file",
//                "temp_table_1",
//                migrationService,
//                progressMonitor
//            );

            // 在单独的线程中执行迁移任务
//            migrationExecutor.submit(migrationTask);

            // 显示进度对话框
//            ProgressMonitorDialog dialog = new ProgressMonitorDialog(MainWindow.this, "数据迁移", true, true, true);
//            dialog.setMillisToPopup(1000);
//
//            // 在后台线程中执行任务
//            try {
//                dialog.getProgressBar().setIndeterminate(true);
//                dialog.getProgressBar().setValue(0);
//                dialog.getProgressBar().setString("准备开始...");
//
//                // 显示对话框并执行任务
//                dialog.startProgressDialog();
//
//                // 等待任务完成
//                while (!migrationTask.isDone()) {
//                    Thread.sleep(100);
//                    // 更新进度条和状态信息
//                    dialog.getProgressBar().setValue(progressMonitor.getPercentage());
//                    dialog.getProgressBar().setString(progressMonitor.getStatusMessage());
//                }
//
//                dialog.close();
//
//                // 检查是否有异常
//                if (migrationTask.hasError()) {
//                    throw migrationTask.getError();
//                }
//
//                // 显示完成消息
//                JOptionPane.showMessageDialog(MainWindow.this, "数据迁移完成！共处理 " + migrationTask.getTotalRecords() + " 条记录", "信息", JOptionPane.INFORMATION_MESSAGE);
//
//            } catch (InterruptedException | MigrationException ex) {
//                String errorMessage = "数据迁移失败: " + ex.getMessage();
//                JOptionPane.showMessageDialog(MainWindow.this, errorMessage, "错误", JOptionPane.ERROR_MESSAGE);
//            }
//        });

//        migrationPanel.add(migrateButton, BorderLayout.NORTH);
//        migrationPanel.add(progressMonitor, BorderLayout.CENTER);

        // 添加菜单栏
        createMenu();

        // Add tabs
        //tabbedPane.addTab("文件选择", filePanel);
        tabbedPane.addTab("映射配置", mappingPanel);
        tabbedPane.addTab("数据库连接", dbPanel);
        //tabbedPane.addTab("数据迁移", migrationPanel);

        add(tabbedPane, BorderLayout.CENTER);
    }

    /**
     * 创建菜单栏
     */
    private void createMenu() {
        // 创建菜单栏
        JMenuBar menuBar = new JMenuBar();
        
        // 文件菜单
        JMenu fileMenu = new JMenu("文件");
        JMenuItem exitItem = new JMenuItem("退出");
        exitItem.addActionListener(e -> System.exit(0));
        fileMenu.add(exitItem);
        
        // 配置菜单
        JMenu configMenu = new JMenu("配置");
        JMenuItem mappingItem = new JMenuItem("映射配置");
        mappingItem.addActionListener(e -> showMappingConfigDialog());
        configMenu.add(mappingItem);
        
        // 数据菜单
        JMenu dataMenu = new JMenu("数据");
        JMenuItem migrateItem = new JMenuItem("开始迁移");
        migrateItem.addActionListener(e -> startMigration());
        dataMenu.add(migrateItem);
        
        // 添加菜单到菜单栏
        menuBar.add(fileMenu);
        menuBar.add(configMenu);
        menuBar.add(dataMenu);
        
        // 设置菜单栏
        setJMenuBar(menuBar);
    }
    
    private void showMappingConfigDialog() {
        // 显示映射配置对话框
        // 假设我们有这些服务的实例
        //ConfigPersistenceService configService = new ConfigPersistenceService();
        ExcelReader excelReader = new ExcelReader();
        MappingRuleDAO mappingRuleDAO = new MappingRuleDAO(dbManager.getConnection());
        
//        MappingConfigDialog dialog = new MappingConfigDialog(this, mappingRuleDAO, configPersistence, excelReader);
//        dialog.setVisible(true);
    }
    
    private void startMigration() {
//        if (migrationService == null) {
//            JOptionPane.showMessageDialog(this, "请先建立数据库连接", "错误", JOptionPane.ERROR_MESSAGE);
//            return;
//        }
        
        // 显示提示信息，实际应替换为真正的迁移逻辑
        JOptionPane.showMessageDialog(this, "正在开始数据迁移流程...");
    }
    
    public static void main(String[] args) {
        // 创建并显示主窗口
        SwingUtilities.invokeLater(() -> {
            MainWindow frame = new MainWindow();
            frame.setVisible(true);
        });
    }

    private void showMigrationError(MigrationException.ExceptionType type, String message, String details) {
        StringBuilder errorDetails = new StringBuilder(message);
        if (details != null && !details.isEmpty()) {
            errorDetails.append("\n\n详细信息:\n").append(details);
        }

        JOptionPane.showMessageDialog(this,
                                      errorDetails.toString(),
                                      "错误 - " + type,
                                      JOptionPane.ERROR_MESSAGE);
    }

    // 内部类：数据迁移任务
    private class MigrationTask implements Runnable {
        private String excelFilePath;
        private String targetTableName;
//        private DataMigrationService migrationService;
//        private MigrationProgressMonitor progressMonitor;
        private int totalRecords;
        private Exception error;
        private boolean done = false;

//        public MigrationTask(String excelFilePath, String targetTableName, DataMigrationService migrationService, MigrationProgressMonitor progressMonitor) {
//            this.excelFilePath = excelFilePath;
//            this.targetTableName = targetTableName;
//            //this.migrationService = migrationService;
//            //this.progressMonitor = progressMonitor;
//        }

        @Override
        public void run() {
            try {
                // 1. 读取Excel数据
                List<Map<String, Object>> rawData = excelReader.readExcel(new File(excelFilePath));
                totalRecords = rawData.size();
                //progressMonitor.updateTotalRecords(totalRecords);

                // 2. 获取映射规则
                List<MappingRule> rules = mappingRuleDAO.getAllRules();

                // 3. 应用映射规则转换数据
                List<Map<String, Object>> transformedData = new DataTransformationService(dbManager).transformData(rawData, rules);

                // 4. 创建临时表
                Map<String, String> columns = new HashMap<>();
                for (MappingRule rule : rules) {
                    columns.put(rule.getTargetField(), getSqlType(rule.getConversionType()));
                }
                dbManager.createTemporaryTable(targetTableName, columns);

                // 5. 批量插入数据（分批处理）
                int batchSize = 1000;
                for (int i = 0; i < transformedData.size(); i += batchSize) {
                    int end = Math.min(i + batchSize, transformedData.size());
                    List<Map<String, Object>> batch = transformedData.subList(i, end);
                    dbManager.batchInsert(targetTableName, batch);
                    updateProgress(batch.size());
                }

                // 完成
//                progressMonitor.migrationComplete();

            } catch (Exception ex) {
                error = ex;
//                progressMonitor.migrationFailed(ex.getMessage());
            } finally {
                done = true;
            }
        }

        private void updateProgress(int recordsProcessed) {
//            progressMonitor.updateProgress(recordsProcessed);
        }

        public boolean isDone() {
            return done;
        }

        public boolean hasError() {
            return error != null;
        }

        public Exception getError() {
            return error;
        }

        public int getTotalRecords() {
            return totalRecords;
        }
    }

    // 辅助方法：获取SQL类型
    private String getSqlType(String javaType) {
        switch (javaType) {
            case "Integer":
                return "INT";
            case "Long":
                return "BIGINT";
            case "Double":
            case "BigDecimal":
                return "DECIMAL(19,4)";
            case "LocalDate":
            case "LocalDateTime":
                return "DATETIME";
            default:
                return "VARCHAR(255)";
        }
    }
}